package cn.cjlmonster.demo02.ui;

import android.graphics.Color;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

import cn.cjlmonster.demo02.R;
import cn.cjlmonster.demo02.base.BaseAppCompatActivity;
import cn.cjlmonster.demo02.fragment.ItemFragment;

/**
 * This project is Demo02
 * Created by cjl on 2021/12/5 2:49 下午.
 */

public class V2FragmentActivity extends BaseAppCompatActivity {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_v2_fragment;
    }

    @Override
    protected boolean canBack() {
        return true;
    }

    @Override
    protected void initView() {
        TabLayout tabLayout = findViewById(R.id.tabLayout);
        ViewPager2 viewPager2 = findViewById(R.id.viewPager2);

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(ItemFragment.getInstance(Color.GREEN, "测试1"));
        fragments.add(ItemFragment.getInstance(Color.BLUE, "测试2"));
        fragments.add(ItemFragment.getInstance(Color.YELLOW, "测试3"));
//        fragments.add(ItemFragment.getInstance(Color.MAGENTA, "测试4"));
//        fragments.add(ItemFragment.getInstance(Color.CYAN, "测试5"));
//        fragments.add(ItemFragment.getInstance(Color.CYAN, "测试6"));
//        fragments.add(ItemFragment.getInstance(Color.CYAN, "测试7"));
//        fragments.add(ItemFragment.getInstance(Color.CYAN, "测试8"));
//        fragments.add(ItemFragment.getInstance(Color.CYAN, "测试9"));
//        fragments.add(ItemFragment.getInstance(Color.CYAN, "测试10"));
        
        MyPageAdapter adapter = new MyPageAdapter(this, fragments);

        viewPager2.setAdapter(adapter);
        viewPager2.setOffscreenPageLimit(fragments.size());

        TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager2, true, (tab, position) -> tab.setText("tab" + (position + 1)));
        mediator.attach();

    }

    static class MyPageAdapter extends FragmentStateAdapter {

        private final List<Fragment> fragments;

        public MyPageAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragments) {
            super(fragmentActivity);
            this.fragments = fragments;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragments.get(position);
        }

        @Override
        public int getItemCount() {
            return fragments.size();
        }
    }
}
